package com.crm.service.impl;

import com.crm.dto.LoginDto;
import com.crm.exception.BaseException;
import com.crm.mapper.LoginMapper;
import com.crm.pojo.User;
import com.crm.service.LoginService;
import com.crm.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @ClassName LoginServiceImpl
 * @Description
 * @Author 19632
 * @Date 2024/10/26 21:35
 * @Version
 **/
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public String login(LoginDto loginDto) {
        if (loginDto == null) {
            //参数异常
            throw new BaseException("账户或密码错误");
        }
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        loginDto.setPassword(md5DigestAsHex);
        User user = loginMapper.selectOne(loginDto);

        if (user == null) { //代表用户不存在得
            throw new BaseException("账户或密码错误");
        }

        if (!md5DigestAsHex.equals(loginDto.getPassword())) { //代表密码错误
            throw new BaseException("账户或密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getUserId());
        map.put("username",user.getUsername());
        String token = JwtUtils.generateJwt(map);
        return token;
    }

    @Override
    public void logout() {

    }
}
